package com.wushijia.designpatterns.observer.good.event;

import com.wushijia.designpatterns.observer.bug.LotteryResult;
import com.wushijia.designpatterns.observer.good.event.listen.EventListen;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//被观察者
public class EventManager {

  Map<Enum<EventType>, List<EventListen>> listenMap = new HashMap<>();

  public EventManager(Enum<EventType>... operations) {
    for (Enum<EventType> operation : operations) {
      listenMap.put(operation, new ArrayList<>());
    }
  }

  public enum EventType {
    Message,
    MQ
  }

  //订阅
  public void subscribe(Enum<EventType> eventType, EventListen eventListen) {
    List<EventListen> eventListens = listenMap.get(eventType);
    eventListens.add(eventListen);
  }

  //取消订阅
  public void unSubscribe(Enum<EventType> eventType, EventListen eventListen) {
    List<EventListen> eventListens = listenMap.get(eventType);
    eventListens.remove(eventListen);
  }

  //通知
  public void notify(Enum<EventType> eventType, LotteryResult result) {
    List<EventListen> eventListens = listenMap.get(eventType);
    for (EventListen eventListen : eventListens) {
      eventListen.doEvent(result);
    }
  }
}
